package utils

import (
	"log"

	registry "golang.org/x/sys/windows/registry"
)

type Registry struct{}

var keys = []string{"HKCU", "HKLM", "HKU", "HKCR"}

func ConvertKey(category string) registry.Key {
	var h_key registry.Key
	switch category {
	case "HKLM":
		h_key = registry.LOCAL_MACHINE
	case "HKCR":
		h_key = registry.CLASSES_ROOT
	default:
		h_key = registry.CURRENT_USER
	}
	return h_key
}

func (r Registry) GetString(category string, path string,
	key string) string {
	h_key := ConvertKey(category)
	k, err := registry.OpenKey(h_key,
		path, registry.QUERY_VALUE)
	if err != nil {
		log.Fatal(err)
	}
	defer k.Close()

	s, _, err := k.GetStringValue(key)
	if err != nil {
		log.Fatal(err)
	}
	return s
}

func (r Registry) CreateKey(category string, path string) (registry.Key, bool) {
	h_key := ConvertKey(category)
	k, isExists, err := registry.CreateKey(h_key,
		path, registry.ALL_ACCESS)
	if err != nil {
		log.Fatal(err)
	}
	return k, isExists
}

func (r Registry) SetString(category string, path string,
	key string, value string) error {
	h_key := ConvertKey(category)
	k, err := registry.OpenKey(h_key,
		path, registry.ALL_ACCESS)
	if err != nil {
		log.Fatal(err)
	}
	defer k.Close()

	return k.SetStringValue(key, value)
}
